var ConstellationsModel = function() {
	var self = this;
	this.model = {}
	this.changed = new signals.Signal();

 	this.post = function(m) {
 		self.model = m
		$.ajax({
			type: "GET",
			url: URLBASE+'/get_upload_url/',
			contentType: 'application/json',
			dataType: 'json'
		}).error(function(e) { 
			console.log("[sendForm] init error", e)
		}).done(function (data) {
			self.sendData(self.model, data)
		});
	}

	this.sendData = function(model, upload_url) {
		// console.log('sendData', model)
		var formData = new FormData();
		formData.append("name", model.name);
		formData.append("username", model.username);
		formData.append("color", model.color);
		formData.append("stars", String(model.stars))
		// console.log(String(model.stars))
		
		formData.append("file", dataURItoBlob(model.file));

		$.ajax({
		  url: upload_url,
		  type: "POST",
		  data: formData,
		  processData: false,  // tell jQuery not to process the data
		  contentType: false,   // tell jQuery not to set contentType
		  enctype: "multipart/form-data"
		}).error(function(e) { 
			console.log("[sendData] init error", e)
		}).done(function (data) {
			// console.log("CONSTELLATION CREATED", data)
			self.changed.dispatch("sent", data)
		});
	}

	function dataURItoBlob(dataURI) {
	    var byteString = atob(dataURI.split(',')[1]);
	    var ab = new ArrayBuffer(byteString.length);
	    var ia = new Uint8Array(ab);
	    for (var i = 0; i < byteString.length; i++) {
	        ia[i] = byteString.charCodeAt(i);
	    }
	    return new Blob([ab], { type: 'image/png' });
	}
 		


 	this.getConstellations = function() {
 		console.log('[ConstellationsModel] getConstellations()')
 		try {
 			$.ajax({
 				type: "GET",
 				url:URLBASE+'/constellations/',
 				contentType: 'application/json',
 				dataType: 'json'
 			}).error(function(e) { 
 				console.log("[ConstellationsModel] init error", e)
 			}).done(function (data) {
 				// console.log("[ConstellationsModel] Constellations loaded", data.length)
 				self.changed.dispatch("received", data)
 				// self.initConstellations(data)

 			});
 		} catch(e) {
 			console.log("[ConstellationsModel] getNextGame error", e)
 		}
 	}

 	this.getConstellationById = function(id) {
 		// console.log('[ConstellationsModel] getConstellationById()')
 		try {
 			$.ajax({
 				type: "GET",
 				url:URLBASE+'/constellations/'+id,
 				contentType: 'application/json',
 				dataType: 'json'
 			}).error(function(e) { 
 				console.log("[ConstellationsModel] getConstellationById error", e)
 			}).done(function (data) {
 				// console.log("[ConstellationsModel] getConstellationById loaded", data.length)
 				self.changed.dispatch("received_unique", data)
 				// self.initConstellations(data)

 			});
 		} catch(e) {
 			console.log("[ConstellationsModel] getConstellationById error", e)
 		}
 	}


 	
 	
    return this

}
